//
// finReadCsv.cc
// - read CSV data from Yahoo and store them in struct
//
// Requirements:
// - root v3.10
//
// Use:
// > root
// root> .L finReadCsv.cc+
//

#include <stdlib.h>

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

#include "finReadCsv.hh"

// std::vector<quote_s> quotes; ---- not supported in root 3.10!

//
// read comma separated file with financial quotations
// into struct vquotes_s
//

int readCsvQuotes(TString fname, vquotes_s& vquotes)
{
  std::string line;
  float iopen, ihigh, ilow, iclose, ivolume, iadjclose;
  float idate;
  unsigned int iq;

  std::ifstream input(fname);

  if(!input) {
    std::cerr << "Cannot open input file" << fname << std::endl;
    return EXIT_FAILURE;
  }

  unsigned int lineNum(0);
  bool couldNotConvert(false);
  struct tm unixTime;
  memset(&unixTime, 0, sizeof(unixTime));

  iq = 0;
  while(std::getline(input, line)) {
    if (couldNotConvert) {
      std::cerr << "Could not convert line " << lineNum << std::endl;
      std::cerr << "-- " << line << " --" << std::endl;
    }
    lineNum++;
    size_t firstComma = line.find(',');
    if (sscanf(line.substr(firstComma+1).c_str(), "%f,%f,%f,%f,%f,%f",
	       &iopen, &ihigh, &ilow, &iclose, &ivolume, &iadjclose)
	== 6) {
      couldNotConvert = false;
      strptime(line.substr(0,firstComma).c_str(), "%d-%b-%y", &unixTime);
      //--- date in seconds since 1970
      idate = float(mktime(&unixTime));
      //--- divide by 3*10^7 ==> date in pseudo-years
      idate /= 3e7;

#if 0
      std::cout
	<< line.substr(0,firstComma)
	<< " : " << iclose
	<< " - " << idate
	<< " - " << asctime(&unixTime)
	<< std::endl;
#endif

      if (iq<vquotes.maxSize) {
	vquotes.q[vquotes.size++] = quote_s(idate, iclose);
	//--- fill dataset
	// quote.setVal(iclose);
	// time.setVal(idate);
	// data.add(RooArgSet(quote,time));
      }
    } else {
      //--- first line has headers
      if (lineNum>1) {
	couldNotConvert = true;
      }
    }
  }
  return EXIT_SUCCESS;
}

//
// possibly init code
//
int finReadCvs()
{
  return EXIT_SUCCESS;
}
